﻿
#include <string>
#include <iostream>

#ifdef _WIN32

#include <windows.h>


// 将 UTF-8 字符串转换为 ANSI 字符串
std::string UTF8ToANSI(const std::string& utf8) {
  // 1. 将 UTF-8 转换为宽字符（UTF-16）
  int wideSize = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, nullptr, 0);
  if (wideSize == 0) {
    std::cerr << "UTF-8 to WideChar conversion failed!" << std::endl;
    return "";
  }

  std::wstring wideStr(wideSize, 0);
  if (MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &wideStr[0], wideSize) == 0) {
    std::cerr << "UTF-8 to WideChar conversion failed!" << std::endl;
    return "";
  }

  // 2. 将宽字符（UTF-16）转换为 ANSI
  int ansiSize = WideCharToMultiByte(CP_ACP, 0, wideStr.c_str(), -1, nullptr, 0, nullptr, nullptr);
  if (ansiSize == 0) {
    std::cerr << "WideChar to ANSI conversion failed!" << std::endl;
    return "";
  }

  std::string ansiStr(ansiSize, 0);
  if (WideCharToMultiByte(CP_ACP, 0, wideStr.c_str(), -1, &ansiStr[0], ansiSize, nullptr, nullptr) == 0) {
    std::cerr << "WideChar to ANSI conversion failed!" << std::endl;
    return "";
  }

  // 去除末尾的空字符
  ansiStr.pop_back();
  return ansiStr;
}
#else
std::string UTF8ToANSI(const std::string& utf8) {
  std::cerr << "当前系统不是 Windows 系统。" << std::endl;
  return "";
}
#endif